﻿using AutoMapper;
using B.T.BasicData.Domain.RBAC;
using B.T.BasicData.ErrorCode;
using B.T.BasicData.Infraeturcture;
using B.T.BasicData.Read.Api.DTOs;
using B.T.BasicData.Read.Api.RBACServices.IServices;

namespace B.T.BasicData.Read.Api.RBACServices.Services
{
    public class RoleServices : IRoleServices
    {
        private readonly ILogger<RoleServices> logger;
        private readonly IBaseRepository<RolesInfo> roleinfo;
        private readonly IBaseRepository<Role_Permission> role_Permission;
        private readonly IBaseRepository<Permissions> permissions;
        private readonly IMapper mapper;

        public RoleServices(ILogger<RoleServices> logger,IBaseRepository<RolesInfo> roleinfo,IBaseRepository<Role_Permission> role_permission,IBaseRepository<Permissions> permissions,IMapper mapper)
        {
            this.logger = logger;
            this.roleinfo = roleinfo;
            role_Permission = role_permission;
            this.permissions = permissions;
            this.mapper = mapper;
        }


        /// <summary>
        /// 查找角色信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiPaging<RolePermissionDto>> SraechRole(SraechRoleDto dto)
        {
            try
            {
                var res = new ApiPaging<RolePermissionDto>();

                var roleinfose = roleinfo.Getlist().Where(x => x.IsDeleted.Equals(false));

                if (!string.IsNullOrEmpty(dto.RoleName))
                {
                    roleinfose = roleinfose.Where(x => x.RoleName.Contains(dto.RoleName));
                }

                var TotalCount = roleinfose.Count();
                var TotalPage = (int)Math.Ceiling(TotalCount * 1.0 / dto.PageSize);
                var PageData = roleinfose.OrderByDescending(x => x.RolesId).Skip((dto.PageIndex - 1) * dto.PageSize).Take(dto.PageSize).ToList();

                logger.LogInformation($"查询到 {TotalCount} 条角色记录，当前页 {dto.PageIndex}，每页 {dto.PageSize} 条");

                //数据转换
                var data = mapper.Map<List<RolePermissionDto>>(PageData);

                foreach (var item in data)
                {
                    try
                    {
                        logger.LogInformation($"处理角色 {item.RolesId} 的权限信息");
                        
                        var role_Permissionse = role_Permission.Getlist()
                            .Where(x => x.RolesId.Equals(item.RolesId) && !x.IsDele)
                            .Select(x => x.PermissionsId)
                            .ToList();

                        logger.LogInformation($"角色 {item.RolesId} 有 {role_Permissionse.Count} 个权限ID: {string.Join(",", role_Permissionse)}");

                        item.PermissionId = role_Permissionse;

                        if (role_Permissionse.Any())
                        {
                            var permissionsse = permissions.Getlist()
                                .Where(x => role_Permissionse.Contains(x.PermissionsId) && !x.IsDeleted)
                                .Select(x => x.PermissionName)
                                .ToList();

                            logger.LogInformation($"角色 {item.RolesId} 的权限名称: {string.Join(",", permissionsse)}");
                            item.PermissionName = permissionsse;
                        }
                        else
                        {
                            item.PermissionName = new List<string>();
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.LogError($"处理角色 {item.RolesId} 权限时出错: {ex.Message}");
                        item.PermissionName = new List<string>();
                    }
                }

                res.TotalCount = TotalCount;
                res.TotalPage = TotalPage;
                res.PageData = data;

                res.code = ApiREunm.Ok;
                res.msg = "查找角色信息成功";
                return res;
            }
            catch (Exception ex)
            {
                logger.LogError("=>" + ex.Message);
                throw ex;
            }
        }
    }
}
